//
//  PHAsset+Downscaling.m
//  OntheRoadV4
//
//  Created by ranjingfu on 15/12/15.
//  Copyright © 2015年 EricHuang. All rights reserved.
//

#import "PHAsset+Downscaling.h"
#import "ALAssetsGroupEnumerator.h"
#import "QWImageMangerConfig.h"
@implementation PHAsset (Downscaling)


- (id)assetURL
{
    return self.localIdentifier;
}
- (UIImage*)minThumbnail
{
    __block UIImage *tempImg = nil;
    PHImageRequestOptions  *opti = [[PHImageRequestOptions alloc] init];
    opti.networkAccessAllowed = NO;
    opti.synchronous = YES;
    opti.resizeMode = PHImageRequestOptionsResizeModeNone;
    PHCachingImageManager *imageManager = [[ALAssetsGroupEnumerator sharedInstance] imageManager];
    [imageManager requestImageForAsset:self
                            targetSize:CGSizeMake(120*SCREEN_SCALE, 120*SCREEN_SCALE)
                           contentMode:PHImageContentModeDefault
                               options:opti
                         resultHandler:^(UIImage *result, NSDictionary *info) {
                             
                             //DebugLog(@"minThumbnail result:%@ info:%@",result,info);
                             if (result)
                             {
                                 tempImg = result;
                             }else
                             {
                                 //DebugLog(@"minThumbnail:%@",info);
                             }
                             
                         }];
    
    return tempImg;
}

- (CGSize)dimensions
{
    
    CGSize size = CGSizeMake(self.pixelWidth, self.pixelHeight);
  //  //DebugLog(@"dimensions:%@",[NSValue valueWithCGSize:size]);
    return size;
}
- (NSInteger)maxShareImageSizeForOTR
{
    
    CGSize imgSize =  [self dimensions];
    if (imgSize.height * imgSize.width <= 4000000) {
        return MAX(imgSize.width, imgSize.height);
    } else {
        CGFloat scale = imgSize.height * imgSize.width / 4000000;
        scale = sqrt(scale);
        
        NSInteger width = roundf(imgSize.width / scale);
        width = ((width % 2 == 0) ? width : width + 1);
        
        NSInteger height = roundf(imgSize.height / scale);
        height = ((height % 2 == 0) ? height : height + 1);
        
        return MAX(width, height);
    }
}

- (NSInteger)screenThumbnailSizeForOTR
{
    CGSize imgSize = [self dimensions];
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenScale = [UIScreen mainScreen].scale;
    
    if (imgSize.height > imgSize.width * screenHeight / screenWidth) {
        return (screenHeight - 100) * screenScale;
    } else {
        return screenWidth * screenScale;
    }
}

- (NSInteger)screenMinSizeForOTR
{
    CGFloat screenWidth = 67;
    CGFloat screenScale = [UIScreen mainScreen].scale;
    
    return screenWidth * screenScale;
}

- (UIImage *)thumbnailWithMaxPixelSize:(NSUInteger)maxSize orientation:(UIImageOrientation)orientation
{
    NSParameterAssert(maxSize > 0);
    __block NSData  *data = nil;
    PHImageRequestOptions  *opti = [[PHImageRequestOptions alloc] init];
    opti.networkAccessAllowed = NO;
    opti.version = PHImageRequestOptionsVersionCurrent;
    opti.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    opti.resizeMode = PHImageRequestOptionsResizeModeFast;
    opti.synchronous = YES;
    PHCachingImageManager *imageManager = [[ALAssetsGroupEnumerator sharedInstance] imageManager];
    [imageManager requestImageDataForAsset:self
                                   options:opti
                             resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info)
     {
         data = imageData;
         
         //DebugLog(@"imageData:%@ \n\ndataUTI:%@ info:%@",imageData,dataUTI,info);
     }];
    
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    CFDictionaryRef options;
    if (maxSize > 0) {
        options = (__bridge CFDictionaryRef) @{
                                               (NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                               (NSString *)kCGImageSourceThumbnailMaxPixelSize : [NSNumber numberWithInteger:maxSize],
                                               (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
                                               };
    } else {
        options = (__bridge CFDictionaryRef) @{
                                               (NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                               (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
                                               };
    }
    
    CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(source, 0, options);
    
    CFRelease(source);
    
    
    if (!imageRef) {
        return nil;
    }
    
    UIImage *toReturn = [UIImage imageWithCGImage:imageRef scale:1.0f orientation:orientation];
    
    CFRelease(imageRef);
    return toReturn;
}

/**
 *  当前方法没有实现  如有需要，请实现
 *
 *  @param size max size
 *
 *  @return data
 */
- (NSData *)thumbnaiDataWithMaxPixelSize:(NSUInteger)size
{
    NSParameterAssert(self != nil);
    return nil;
}

-(BOOL)resultForSelect:(SEL)select asset:(NSObject*)asset
{
    IMP imp = [asset methodForSelector:select];
    if (imp)
    {
        BOOL (*func)(id, SEL) = (void *)imp;
        BOOL  result = func(asset, select);
        return result;
    }
    
    return NO;
}



-(long long)longResultForSelect:(SEL)select asset:(NSObject*)asset
{
    if (asset == nil)
    {
        return 0;
    }
    IMP imp = [asset methodForSelector:select];
    long long (*func)(id, SEL) = (void *)imp;
    long long  result = func(asset, select);
    return result;
}

/**
 *  本方法有使用未公开的API
 *
 *  @return 相册里是否有本地源文件
 */
-(BOOL)hasOriginalFile
{
    BOOL isiCloudFile =  [self resultForSelect:@selector(isCloudPhotoLibraryAsset) asset:self];
    if (isiCloudFile)
    {
        long cloudSharedAssetPlaceholderKind =  [[self valueForKeyPath:@"cloudPlaceholderKind"] longLongValue];//[self longResultForSelect:@selector(cloudPlaceholderKind) asset:self];
        
        //DebugLog(@"cloudSharedAssetPlaceholderKind:%lld isiCloudFile:%d",cloudSharedAssetPlaceholderKind,isiCloudFile);
        
        NSInteger maxPlaceholderKind = 5;
        if (self.pixelWidth*self.pixelHeight <= 640*960)
        {
            maxPlaceholderKind = 3;
        }
        if (cloudSharedAssetPlaceholderKind >= maxPlaceholderKind)
        {
            return YES;
        }else
        {
            return NO;
        }
    }
    
    return YES;
}

- (BOOL)writeData:(NSData *)imageData toFileurl:(NSURL*)fileURL metadata:(NSDictionary *)metadata
{
    UIImage *image = [UIImage imageWithData:imageData];
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
    NSMutableDictionary * sourceDic = [NSMutableDictionary dictionary];

    NSDictionary  *source_metadata = (NSDictionary *)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source,0,NULL));
    [sourceDic addEntriesFromDictionary:source_metadata];
    [sourceDic addEntriesFromDictionary:metadata];
    
    CFStringRef UTI = CGImageSourceGetType(source);
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, UTI, 1, NULL);
    CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)sourceDic);
    CGImageDestinationFinalize(destination);
    CFRelease(source);
    CFRelease(destination);
    return YES;
}



- (BOOL)writeAssetFullResolutionImageToFile:(NSString *)filePath
{
    NSParameterAssert(self != nil);
    @autoreleasepool {
        
        __block NSData  *data  = nil;
        PHImageRequestOptions  *opti = [[PHImageRequestOptions alloc] init];
        opti.networkAccessAllowed = NO;
        opti.synchronous = YES;
        opti.resizeMode = PHImageRequestOptionsResizeModeExact;
        opti.version =  PHImageRequestOptionsVersionOriginal;
        opti.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
        PHCachingImageManager *imageManager = [[ALAssetsGroupEnumerator sharedInstance] imageManager];

        [imageManager requestImageDataForAsset:self
                                       options:opti
                                 resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info)
         {
             data = imageData;
             
             UIImage *image = [UIImage imageWithData:data scale:1.0f];
             
             image = [UIImage imageWithCGImage:image.CGImage scale:1.0f orientation:7];
             
             NSLog(@"XXXXX");
         }];
        
       // NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        return [data writeToFile:filePath atomically:YES];
    }
}


- (BOOL)writeAssetThumbnailImageToFile:(NSString *)filePath maxSize:(NSInteger)maxSize
{
    
    NSParameterAssert(self != nil);
    NSParameterAssert(maxSize > 0);
    @autoreleasepool {
        
//        BOOL imageIOSupportsFilter = !([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] == NSOrderedAscending);
        
        __block NSData  *data  = nil;
        __block NSString *UTI = nil;
        
        PHImageRequestOptions  *opti = [[PHImageRequestOptions alloc] init];
        opti.networkAccessAllowed = NO;
        opti.version = PHImageRequestOptionsVersionOriginal;
        opti.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        opti.resizeMode = PHImageRequestOptionsResizeModeExact;
        opti.synchronous = YES;
        PHCachingImageManager *imageManager = [[ALAssetsGroupEnumerator sharedInstance] imageManager];
        [imageManager requestImageDataForAsset:self
                                       options:opti
                                 resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info)
         {
             data = imageData;
             UTI = dataUTI;
         }];
        
        NSInteger picWidth = [self dimensions].width;
        NSInteger picHeight = [self dimensions].height;
        
        CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
        NSMutableDictionary * sourceDic = [NSMutableDictionary dictionary];
        NSDictionary *metadata = (NSDictionary *)CFBridgingRelease(CGImageSourceCopyProperties(source, NULL));
        NSDictionary  *source_metadata = (NSDictionary *)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source,0,NULL));
        [sourceDic addEntriesFromDictionary: metadata];
        [sourceDic addEntriesFromDictionary:source_metadata];
        
        [sourceDic setObject:@(1) forKey:(NSString *)kCGImagePropertyOrientation];
        [sourceDic setObject:@(picWidth) forKey:(NSString*)kCGImagePropertyPixelWidth];
        [sourceDic setObject:@(picHeight) forKey:(NSString*)kCGImagePropertyPixelHeight];
        
        
        NSMutableDictionary *mutableExitDict = [source_metadata valueForKey:(NSString *)kCGImagePropertyExifDictionary];
        if (mutableExitDict) {
            mutableExitDict = [mutableExitDict mutableCopy];
            //[mutableExitDict setValue:@(1) forKey:(NSString *)kCGImagePropertyTIFFOrientation];
            [mutableExitDict setObject:@(picWidth) forKey:(NSString*)kCGImagePropertyExifPixelXDimension];
            [mutableExitDict setObject:@(picHeight) forKey:(NSString*)kCGImagePropertyExifPixelYDimension];
            [sourceDic setValue:mutableExitDict forKey:(NSString *)kCGImagePropertyExifDictionary];
        }
        
        
        NSMutableDictionary *mutableTIFFDict = [source_metadata valueForKey:(NSString *)kCGImagePropertyTIFFDictionary];
        if (mutableTIFFDict) {
            mutableTIFFDict = [mutableTIFFDict mutableCopy];
            [mutableTIFFDict setObject:@(1) forKey:(NSString*)kCGImagePropertyTIFFOrientation];
            [sourceDic setValue:mutableTIFFDict forKey:(NSString *)kCGImagePropertyTIFFDictionary];
        }
        
        CFDictionaryRef options;
        if (maxSize > 0) {
            options = (__bridge CFDictionaryRef) @{
                                                   (NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                                   (NSString *)kCGImageSourceThumbnailMaxPixelSize : [NSNumber numberWithInteger:maxSize],
                                                   (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
                                                   };
        } else {
            options = (__bridge CFDictionaryRef) @{
                                                   (NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                                   (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
                                                   };
        }
        
        //DebugLog(@"writeAssetThumbnailImageToFile:%@ maxSize:%d",filePath,maxSize);
        CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(source, 0, options);
        
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, (__bridge CFStringRef)UTI, 1, NULL);
        CGImageDestinationAddImage(destination, imageRef, (__bridge CFDictionaryRef)sourceDic);
        CGImageDestinationFinalize(destination);
        CFRelease(source);
        CFRelease(destination);
        CFRelease(imageRef);
        data = nil;
        
        return YES;
    }
    return YES;
}

@end
